package com.xut.consumer;

import com.rabbitmq.client.*;
import com.xut.common.constant.MqConstant;
import com.xut.common.factory.MqConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class ConsumerClient {

    public static void basicConsumer() throws IOException, TimeoutException {

        Connection connect = MqConnectionFactory.getConnection();
        Channel channel = connect.createChannel();
        channel.queueDeclare(MqConstant.QUEUE_NAME, true, false, false, null);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("路由key为: " + envelope.getRoutingKey());
                System.out.println("交换机为: " + envelope.getExchange());
                System.out.println("消息id为: " + envelope.getDeliveryTag());
                System.out.println("接收到的消息为: " + new String(body, "utf-8"));
            }
        };

        // 监听队列
        channel.basicConsume(MqConstant.QUEUE_NAME, true, consumer);


    }

    public static void main(String[] args) throws IOException, TimeoutException {
        basicConsumer();
    }

}
